/**
 * created by 小卷毛, 2020/12/11
 * Copyright (c) 2020, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.sgcc.pda.mdrh.task.safe.router;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.sgcc.pda.lib_tools_database.bean.other.AppNoForPlan;
import com.sgcc.pda.lib_tools_database.bean.other.TicketMeasure;
import com.sgcc.pda.lib_tools_database.bean.other.TicketMeasureSave;
import com.sgcc.pda.lib_tools_database.bean.ticket.LocalImage;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketDetail;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketMeeting;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketPermit;
import com.sgcc.pda.lib_tools_database.factory.AppNoForPlanImpl;
import com.sgcc.pda.lib_tools_database.factory.JSResultUtil;
import com.sgcc.pda.lib_tools_database.factory.LocalImageImpl;
import com.sgcc.pda.lib_tools_database.factory.RiskHttpStateImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketDetailImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketLocalUtil;
import com.sgcc.pda.lib_tools_database.factory.TicketMeasureImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketMeasureSaveImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketMeetingImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketPermitImpl;
import com.sgcc.pda.mdrh.task.safe.entity.ImageResult;
import com.sgcc.pda.mdrh.task.safe.entity.OfflineParam;
import com.sgcc.pda.mdrh.task.safe.entity.TicketDetailResult;
import com.sgcc.pda.mdrh.task.safe.entity.TicketSaveInfo;
import com.sgcc.pda.mdrh.task.safe.oss.OSSHelper;
import com.sgcc.pda.mdrh.task.safe.oss.OnOSSStatusListener;
import com.sgcc.pda.mdrh.task.safe.util.HttpUtil;
import com.sgcc.pda.mdrh.utils.ToolGson2;
import com.sgcc.pda.mdrh.zoom.router.BaseOperateRouter;
import com.sgcc.pda.model.web.request.PostDataCallbackRequest;
import com.sgcc.pda.sdk.entity.BaseEntity;
import com.sgcc.pda.sdk.utils.NetWorkUtil;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;
import com.sgcc.pda.tools.JsonUtils;
import com.sgcc.pda.tools.SPUtils;
import com.sgcc.pda.web.impl.HttpCallbackInterface;
import com.sgcc.pda.web.service.SingleThreadUtil;
import com.sgcc.pda.web.service.ZoomWebControler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 描 述：离线路由逻辑处理
 * 作 者：小卷毛  2020-12-11 13:54
 * 修改描述：增加查询字段，风险点附件表增加模式和修改上传逻辑
 * 修 改 人：
 * 修改版本：v1.2.1
 */
public class OfflineRouter {

    // 本地图片
    private LocalImageImpl mLocalImageDao;
    // 本地工作票
    private TicketDetailImpl mTicketDetail;
    // 本地工作票许可、终结
    private TicketPermitImpl mTicketPermit;
    // 本地班前会结束
    private TicketMeetingImpl mTicketMeeting;
    // 本地工单和工作计划关联
    private AppNoForPlanImpl mAppNoForPlan;
    // 本地风险点取证信息
    private TicketMeasureSaveImpl mRiskSave;
    // 待上传风险点数据表
    private RiskHttpStateImpl mRiskHttp;
    // 工作票防范措施数据表
    private TicketMeasureImpl mTicketMeasure;

    public OfflineRouter() {
        mLocalImageDao = new LocalImageImpl();
        mTicketDetail = new TicketDetailImpl();
        mTicketPermit = new TicketPermitImpl();
        mTicketMeeting = new TicketMeetingImpl();
        mAppNoForPlan = new AppNoForPlanImpl();
        mRiskSave = new TicketMeasureSaveImpl();
        mRiskHttp = new RiskHttpStateImpl();
        mTicketMeasure = new TicketMeasureImpl();
    }

    /**
     * 离线路由分支处理
     *
     * @param context          上下文
     * @param request          请求参数
     * @param completeListener 回调
     */
    public void handleResult(
            final Context context,
            PostDataCallbackRequest request,
            final BaseOperateRouter.CompleteListener completeListener) {
        OfflineParam param = null;
        if (!"submitRiskPoint".equals(request.getAction())) {
            // 解析参数
            param = ToolGson2.getBean(
                    request.getRequestParams(),
                    OfflineParam.class
            );
        }

        switch (request.getAction()) {
            // 离线工作票详情数据
            case "loadTicketDetail":
                if (param != null) {
                    // 查询本地数据库
                    final String result = JSResultUtil.getTicketDetail(param.getRecordId());

                    try {
                        // 判断是否网络连接
                        boolean isConnected = NetWorkUtil.getInstance().isConnected(context);
                        JSONObject obj = new JSONObject(result);
                        // 有网状态下是否查询到数据
                        if (isConnected
                                && "40".equals(obj.optString("RT_F"))) {
                            // 当前工作票id
                            final String wtId = param.getRecordId();

                            // 本地未查询到数据时重新请求接口
                            getSingleTicket(
                                    context,
                                    param.getRecordId(),
                                    new IUploadCallback() {
                                        @Override
                                        public void onDone() {
                                            // 回调结果给微应用
                                            completeListener.complete(
                                                    1,
                                                    JSResultUtil.getTicketDetail(wtId)
                                            );
                                        }

                                        @Override
                                        public void onFail() {
                                            // 回调结果给微应用
                                            completeListener.complete(1, result);
                                        }
                                    });
                        } else {
                            // 回调结果给微应用
                            completeListener.complete(1, result);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            // 工作票许可提交
            case "submitTicketPermit":
                if (param != null
                        && param.getPermitParam() != null) {
                    handlePermitData(context, param.getPermitParam(), completeListener);
                }
                break;
            // 班前会结束提交
            case "submitMeetingEnd":
                if (param != null
                        && param.getMeetingParam() != null) {
                    handleMeetingEnd(context, param.getMeetingParam(), completeListener);
                }
                break;
            // 工作票终结提交
            case "submitTicketEnd":
                if (param != null
                        && param.getPermitParam() != null) {
                    handleEndData(context, param.getPermitParam(), completeListener);
                }
                break;
            // 知识库风险点取证数据提交
            case "submitRiskPoint":
                try {
                    TicketSaveInfo saveData = ToolGson2.getBean(
                            request.getRequestParams(),
                            TicketSaveInfo.class
                    );

                    handleRiskRecord(context, saveData, completeListener);
                } catch (Exception e) {
                    e.printStackTrace();

                    // 回调结果给微应用
                    completeListener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new BaseEntity(
                                            "0",
                                            "数据保存失败！"
                                    )
                            )
                    );
                }
                break;
            // 风险点取证保存触发本地工作票
            case "saveTicketRiskResult":
                if (param != null) {
                    // 更新本地工作票信息
                    TicketDetail data =
                            new TicketLocalUtil().getTicketDetailByNo(param.getWtNo());

                    if (data != null) {
                        if ("1".equals(param.getIsChk())
                                && "1".equals(data.getRISK_CHK_REQUIRED())) {
                            // 更新本地风险点状态
                            data.setEND_MSG("");

                            // 更新工作票详情
                            mTicketDetail.update(data);
                        }

                        // 回调结果给微应用
                        completeListener.complete(
                                1,
                                ToolGson2.getJsonStr(
                                        new BaseEntity(
                                                "1",
                                                "成功！"
                                        )
                                )
                        );
                    }
                }
                break;
            // 工作票申请延期更新
            case "updateTicketDelay":
                if (param != null
                        && param.getDelayParam() != null) {
                    // 更新本地工作票信息
                    TicketDetail data = new TicketLocalUtil()
                            .getTicketDetail(param.getDelayParam().getRECORD_ID());

                    if (data != null) {
                        // 更新本地延期状态
                        data.setWT_DELAY("1");

                        // 更新工作票详情
                        mTicketDetail.update(data);

                        // 回调结果给微应用
                        completeListener.complete(
                                1,
                                ToolGson2.getJsonStr(
                                        new BaseEntity(
                                                "1",
                                                "成功！"
                                        )
                                )
                        );
                    }
                }
                break;
            // 查询设施列表
            case "getTicketFaciList":
                if (param != null) {
                    completeListener.complete(
                            1,
                            JSResultUtil.getTicketFaciList(param.getWtType())
                    );
                }
                break;
            // 手动触发获取本地工作票
            case "getLocalTicketByHand":
                if (param != null
                        && param.getRecordId() != null) {
                    getSingleTicket(
                            context,
                            param.getRecordId(),
                            null);
                } else getTicketByHand(context);
                // 手动触发获取本地工作票防范措施
            case "getLocalMeasureByHand":
                if (param != null
                        && param.getWtNo() != null)
                    getMeasuresByTicket(context, param.getWtNo());

                // 回调结果给微应用
                completeListener.complete(
                        1,
                        ToolGson2.getJsonStr(
                                new BaseEntity(
                                        "1",
                                        "成功！"
                                )
                        )
                );
                break;
            // OSS签名获取真实URL
            case "getRealUrl":
                if (param != null
                        && param.getImgs() != null) {
                    // 图片集合
                    ArrayList<String> items = new ArrayList<>();

                    for (String item : param.getImgs())
                        items.add(OSSHelper.getInstance().getRealUrl(item));

                    // 回调结果给微应用
                    completeListener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new ImageResult(
                                            "1",
                                            "签名成功！",
                                            items
                                    )
                            )
                    );
                }
                break;
        }
    }

    /**
     * 工作票许可网络逻辑处理
     *
     * @param context  上下文
     * @param param    提交参数
     * @param listener 回调
     */
    private void handlePermitData(
            final Context context,
            final TicketPermit param,
            final BaseOperateRouter.CompleteListener listener) {
        final List<LocalImage> images = param.getSignDataList();
        // 待上传列表集合
        List<LocalImage> items = new ArrayList<>();

        if (images != null) {
            for (LocalImage item : images) {
                if (TextUtils.isEmpty(item.getAttachSrc())) {
                    // 回调结果给微应用
                    listener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new BaseEntity(
                                            "40",
                                            "数据参数提交错误！"
                                    )
                            )
                    );
                    return;
                }

                // 初始赋值
                item.setParentId(param.getRECORD_ID());
                item.setAttachMode("1"); //工作票许可模式
                item.setAttachId(item.getWtPersonType());
                item.setAttachName("wtPersonType");
                item.setAttachLocal("");
                if (item.getAttachSrc()
                        .startsWith("storage", 1)) {
                    item.setAttachStatus("01"); //待上传

                    items.add(item);
                } else {
                    item.setAttachStatus("03"); //待下载
                }
            }

            // 判断是否网络连接
            boolean isConnected = NetWorkUtil.getInstance().isConnected(context);
            if (isConnected) {
                uploadPicture(
                        items,
                        new IUploadCallback() {
                            @Override
                            public void onDone() {
                                // 图片数据插入数据库
                                mLocalImageDao.insertList(images);

                                // 网络提交许可数据
                                HttpUtil.submitTicketPermit(
                                        context,
                                        param,
                                        new HttpCallbackInterface() {
                                            @Override
                                            public void httpSuccess(String result) {
                                                // 设置已提交状态
                                                param.setWT_IS_PERMIT("1");
                                                handlePermitResult(param, listener);
                                            }

                                            @Override
                                            public void httpFailed(int errorCode, String errorMsg) {
                                                Log.e("onFail-permit:", errorCode + "：" + errorMsg);

                                                // 回调结果给微应用
                                                listener.complete(
                                                        1,
                                                        ToolGson2.getJsonStr(
                                                                new BaseEntity(
                                                                        "31",
                                                                        errorMsg
                                                                )
                                                        )
                                                );
                                            }
                                        }
                                );
                            }

                            @Override
                            public void onFail() {
                                // 回调结果给微应用
                                listener.complete(
                                        1,
                                        ToolGson2.getJsonStr(
                                                new BaseEntity(
                                                        "31",
                                                        "附件上传失败！"
                                                )
                                        )
                                );
                            }
                        });
            } else {
                // 图片数据插入数据库
                mLocalImageDao.insertList(images);
                // 设置待提交状态
                param.setWT_IS_PERMIT("0");
                handlePermitResult(param, listener);
            }
        } else {
            // 回调结果给微应用
            listener.complete(
                    1,
                    ToolGson2.getJsonStr(
                            new BaseEntity(
                                    "40",
                                    "未提交附件信息！"
                            )
                    )
            );
        }
    }

    /**
     * 无网络或成功时许可的处理
     *
     * @param param    提交参数
     * @param listener 回调
     */
    private void handlePermitResult(
            TicketPermit param,
            BaseOperateRouter.CompleteListener listener) {
        param.setWT_MODE("1");
        mTicketPermit.insert(param);

        // 更新本地工作票信息
        TicketDetail data = new TicketLocalUtil()
                .getTicketDetail(param.getRECORD_ID());

        // 更新版本号
        int verison = Integer.parseInt(data.getVERSION());
        verison += 1;
        data.setVERSION(String.valueOf(verison));

        // 更新终结提示语
        data.setEND_MSG(
                "1".equals(data.getMEET_REQUIRED())
                        ? "您还未召开班前会！" : "");

        // 更新工作票信息
        data.setWT_STATE("04");
        data.setWT_PERMIT_PER_NAME(param.getWT_PERMIT_PER_NAME());
        data.setWT_ALLOW_TIME(param.getWT_ALLOW_TIME());
        data.setWT_CUSTOMER_NAME(param.getWT_CUSTOMER_NAME());
        data.setWT_SAFE_MEASURE_ADD(param.getWT_SAFE_MEASURE_ADD());

        // 更新供电方许可方式
        switch (param.getWT_RECORD_WAY()) {
            case "01":
                data.setWT_RECORD_WAY("电话");
                break;
            case "02":
                data.setWT_RECORD_WAY("现场");
                break;
            default:
                data.setWT_RECORD_WAY(param.getWT_RECORD_WAY());
                break;
        }

        // 更新客户方许可方式
        switch (param.getWT_ALLOW_WAY()) {
            case "01":
                data.setWT_ALLOW_MODE("电话");
                break;
            case "02":
                data.setWT_ALLOW_MODE("现场");
                break;
            default:
                data.setWT_ALLOW_MODE(param.getWT_ALLOW_WAY());
                break;
        }

        // 更新附件路径
        for (LocalImage item : param.getSignDataList()) {
            // 是否是客户方签字图片
            if ("07".equals(item.getWtPersonType())
                    && "01".equals(item.getWtSignPattern())) {
                data.setATTACH_SRC(
                        TextUtils.isEmpty(item.getAttachLocal())
                                ? item.getAttachSrc() : item.getAttachLocal()
                );
            }

            // 是否是供电方签字图片
            if ("03".equals(item.getWtPersonType())
                    && "01".equals(item.getWtSignPattern())) {
                data.setWT_ATTACH_SRC(
                        TextUtils.isEmpty(item.getAttachLocal())
                                ? item.getAttachSrc() : item.getAttachLocal()
                );
            }
        }

        // 更新工作票详情
        mTicketDetail.update(data);

        // 回调结果给微应用
        listener.complete(
                1,
                ToolGson2.getJsonStr(
                        new BaseEntity(
                                "1",
                                "许可成功！"
                        )
                )
        );
    }

    /**
     * 工作票终结网络逻辑处理
     *
     * @param context  上下文
     * @param param    提交参数
     * @param listener 回调
     */
    private void handleEndData(
            final Context context,
            final TicketPermit param,
            final BaseOperateRouter.CompleteListener listener) {
        final List<LocalImage> images = param.getSignDataList();
        // 待上传列表集合
        List<LocalImage> items = new ArrayList<>();

        if (images != null) {
            for (LocalImage item : images) {
                if (TextUtils.isEmpty(item.getAttachSrc())) {
                    // 回调结果给微应用
                    listener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new BaseEntity(
                                            "40",
                                            "数据参数提交错误！"
                                    )
                            )
                    );
                    return;
                }

                // 初始赋值
                item.setParentId(param.getRECORD_ID());
                item.setAttachMode("4"); //工作票终结附件
                item.setAttachId(item.getWtPersonType());
                item.setAttachName("wtPersonType");
                item.setAttachLocal("");
                if (item.getAttachSrc()
                        .startsWith("storage", 1)) {
                    item.setAttachStatus("01"); //待上传

                    items.add(item);
                } else {
                    item.setAttachStatus("03"); //待下载
                }
            }

            // 判断是否网络连接
            boolean isConnected = NetWorkUtil.getInstance().isConnected(context);
            if (isConnected) {
                uploadPicture(
                        items,
                        new IUploadCallback() {
                            @Override
                            public void onDone() {
                                // 图片数据插入数据库
                                mLocalImageDao.insertList(images);

                                // 网络提交终结数据
                                HttpUtil.submitTicketEnd(
                                        context,
                                        param,
                                        new HttpCallbackInterface() {
                                            @Override
                                            public void httpSuccess(String result) {
                                                // 删除工作票信息
                                                mTicketDetail.deleteById(param.getRECORD_ID());
                                                // 删除待提交数据
                                                mTicketPermit.deleteById(param.getRECORD_ID());

                                                // 回调结果给微应用
                                                listener.complete(
                                                        1,
                                                        ToolGson2.getJsonStr(
                                                                new BaseEntity(
                                                                        "1",
                                                                        "终结成功！"
                                                                )
                                                        )
                                                );
                                            }

                                            @Override
                                            public void httpFailed(int errorCode, String errorMsg) {
                                                Log.e("onFail-end:", errorCode + "：" + errorMsg);

                                                // 回调结果给微应用
                                                listener.complete(
                                                        1,
                                                        ToolGson2.getJsonStr(
                                                                new BaseEntity(
                                                                        "31",
                                                                        errorMsg
                                                                )
                                                        )
                                                );
                                            }
                                        }
                                );
                            }

                            @Override
                            public void onFail() {
                                // 回调结果给微应用
                                listener.complete(
                                        1,
                                        ToolGson2.getJsonStr(
                                                new BaseEntity(
                                                        "31",
                                                        "附件上传失败！"
                                                )
                                        )
                                );
                            }
                        });
            } else {
                // 图片数据插入数据库
                mLocalImageDao.insertList(images);
                // 设置待提交状态
                param.setWT_IS_PERMIT("0");
                param.setWT_MODE("2");
                // 插入待提交数据库
                mTicketPermit.insert(param);

                // 更新本地工作票信息
                TicketDetail data = new TicketLocalUtil()
                        .getTicketDetail(param.getRECORD_ID());
                data.setWT_STATE("05");
                mTicketDetail.update(data);

                // 回调结果给微应用
                listener.complete(
                        1,
                        ToolGson2.getJsonStr(
                                new BaseEntity(
                                        "1",
                                        "终结成功！"
                                )
                        )
                );
            }
        } else {
            // 回调结果给微应用
            listener.complete(
                    1,
                    ToolGson2.getJsonStr(
                            new BaseEntity(
                                    "40",
                                    "未提交附件信息！"
                            )
                    )
            );
        }
    }

    /**
     * 班前会结束网络逻辑处理
     *
     * @param context  上下文
     * @param param    提交参数
     * @param listener 回调
     */
    private void handleMeetingEnd(
            final Context context,
            final TicketMeeting param,
            final BaseOperateRouter.CompleteListener listener) {
        if (param.getITEMS() != null)
            param.setITEMS_STRING(JsonUtils.toJson(param.getITEMS()));

        ArrayList<LocalImage> images = new ArrayList<>();
        // 待上传列表集合
        List<LocalImage> items = new ArrayList<>();

        // 附件列表赋值
        if (param.getFILE_LIST() != null) {
            for (LocalImage item : param.getFILE_LIST()) {
                if (TextUtils.isEmpty(item.getAttachSrc())) {
                    // 回调结果给微应用
                    listener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new BaseEntity(
                                            "40",
                                            "数据参数提交错误！"
                                    )
                            )
                    );
                    return;
                }

                // 初始赋值
                item.setParentId(param.getWT_ID());
                item.setAttachMode("2"); //班前会附件
                item.setAttachStatus("01"); //待上传
                item.setAttachId("");
                item.setAttachName("");
                item.setAttachLocal("");
                items.add(item);
                images.add(item);
            }
        }

        // 签字列表赋值
        if (param.getSIGNS() != null) {
            for (LocalImage item : param.getSIGNS()) {
                if (TextUtils.isEmpty(item.getAttachSrc())) {
                    // 回调结果给微应用
                    listener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new BaseEntity(
                                            "40",
                                            "数据参数提交错误！"
                                    )
                            )
                    );
                    return;
                }

                // 初始赋值
                item.setParentId(param.getWT_ID());
                item.setAttachMode("2"); //班前会附件
                item.setAttachType("01");
                item.setAttachId(item.getOperatorId());
                item.setAttachName("operatorId");
                item.setAttachLocal("");

                if (item.getAttachSrc()
                        .startsWith("storage", 1)) {
                    item.setAttachStatus("01"); //待上传

                    items.add(item);
                } else {
                    // 人脸识别签名时会自动带出网络签名图片
                    item.setAttachStatus("03"); //待下载
                }

                images.add(item);
            }
        }

        if (!images.isEmpty()) {
            // 判断是否网络连接
            boolean isConnected = NetWorkUtil.getInstance().isConnected(context);
            if (isConnected) {
                uploadPicture(
                        items,
                        new IUploadCallback() {
                            @Override
                            public void onDone() {
                                // 网络提交终结数据
                                HttpUtil.submitMeetingEnd(
                                        context,
                                        param,
                                        new HttpCallbackInterface() {
                                            @Override
                                            public void httpSuccess(String result) {
                                                handleMeetingResult(param.getWT_ID(), listener);
                                            }

                                            @Override
                                            public void httpFailed(int errorCode, String errorMsg) {
                                                Log.e("onFail-meeting:", errorCode + "：" + errorMsg);

                                                // 回调结果给微应用
                                                listener.complete(
                                                        1,
                                                        ToolGson2.getJsonStr(
                                                                new BaseEntity(
                                                                        "31",
                                                                        errorMsg
                                                                )
                                                        )
                                                );
                                            }
                                        }
                                );
                            }

                            @Override
                            public void onFail() {
                                // 回调结果给微应用
                                listener.complete(
                                        1,
                                        ToolGson2.getJsonStr(
                                                new BaseEntity(
                                                        "31",
                                                        "附件上传失败！"
                                                )
                                        )
                                );
                            }
                        });
            } else {
                if (param.getITEMS() == null
                        || param.getSIGNS().isEmpty()) {
                    // 回调结果给微应用
                    listener.complete(
                            1,
                            ToolGson2.getJsonStr(
                                    new BaseEntity(
                                            "40",
                                            "数据参数提交错误！"
                                    )
                            )
                    );
                } else {
                    // 图片数据插入数据库
                    mLocalImageDao.insertList(images);
                    // 插入待提交数据库
                    mTicketMeeting.insert(param);

                    handleMeetingResult(param.getWT_ID(), listener);
                }
            }
        } else {
            // 回调结果给微应用
            listener.complete(
                    1,
                    ToolGson2.getJsonStr(
                            new BaseEntity(
                                    "40",
                                    "未提交附件信息！"
                            )
                    )
            );
        }
    }

    /**
     * 无网络或成功时班前会的处理
     *
     * @param wtId     提交参数
     * @param listener 回调
     */
    private void handleMeetingResult(
            String wtId,
            BaseOperateRouter.CompleteListener listener
    ) {
        // 更新本地工作票信息
        TicketDetail data = new TicketLocalUtil().getTicketDetail(wtId);

        if (data != null) {
            if (data.getWT_PERSON_LIST() != null) {
                for (TicketDetail.PersonList item : data.getWT_PERSON_LIST()) {
                    // 设置班前会状态已开
                    item.setIS_MEETING("1");
                }
            }

            // 更新终结提示语
            data.setEND_MSG(
                    "1".equals(data.getRISK_CHK_REQUIRED())
                            ? "您还未进行风险点取证！" : "");

            // 更新工作票详情
            mTicketDetail.update(data);
        }

        // 回调结果给微应用
        listener.complete(
                1,
                ToolGson2.getJsonStr(
                        new BaseEntity(
                                "1",
                                "结束成功！"
                        )
                )
        );
    }

    /**
     * 知识库风险点取证保存逻辑
     *
     * @param context  上下文
     * @param param    提交参数
     * @param listener 回调
     */
    private void handleRiskRecord(
            final Context context,
            final TicketSaveInfo param,
            final BaseOperateRouter.CompleteListener listener
    ) {
        if (param != null
                && param.getMeasures() != null) {
            // 查询本地工单和计划关联表
            AppNoForPlan inner =
                    mAppNoForPlan.getDataByAppNoWithPlanNo(
                            param.getAppNo(),
                            param.getPlanNo(),
                            param.getAppCode(),
                            param.getEomOrderSrc(),
                            param.getWorkTypeNo());

            if (inner != null) {
                param.setAppNo(inner.getAppNo());
                param.setPlanNo(inner.getPlanNo());
                param.setWtNo(inner.getWtNo());
            }

            // 循环遍历赋值，并判断是否上传完图片
            param.setIsChk("1");
            for (TicketMeasureSave item : param.getMeasures()) {
                item.setAppNo(param.getAppNo());
                item.setPlanNo(param.getPlanNo());
                item.setWtNo(param.getWtNo());
                item.setWtStatus(item.getRiskPoints().isEmpty() ? "0" : "1");

                if (item.getRiskPoints().isEmpty()) param.setIsChk("0");
            }

            // 保存到本地数据库
            mRiskSave.insertList(param.getMeasures());

            // 查询本地未上传的风险点图片
            final List<LocalImage> images = mLocalImageDao.findByMode("5");

            // 判断是否网络连接
            boolean isConnected = NetWorkUtil.getInstance().isConnected(context);
            if (isConnected) {
                // 上传风险点图片
                uploadPicture(
                        images,
                        new IUploadCallback() {
                            @Override
                            public void onDone() {
                                // 保存已上传图片信息
                                mLocalImageDao.insertList(images);
                                // 查询本地风险点信息
                                List<TicketMeasureSave> riskList = mRiskSave.findRiskList(
                                        param.getAppNo(),
                                        param.getPlanNo(),
                                        param.getWtNo()
                                );
                                param.setMeasures(riskList);

                                HttpUtil.saveTicketRiskRecordAsync(
                                        context,
                                        param.getAppNo(),
                                        param.getPlanNo(),
                                        param.getWtNo(),
                                        param.getIsChk(),
                                        JsonUtils.toJson(param.getMeasures()),
                                        new HttpCallbackInterface() {
                                            @Override
                                            public void httpSuccess(String result) {
                                                handleRiskResult(param, listener);
                                            }

                                            @Override
                                            public void httpFailed(int errorCode, String errorMsg) {
                                                Log.e("onFail-risk:", errorCode + "：" + errorMsg);

                                                // 回调结果给微应用
                                                listener.complete(
                                                        1,
                                                        ToolGson2.getJsonStr(
                                                                new BaseEntity(
                                                                        "31",
                                                                        errorMsg
                                                                )
                                                        )
                                                );
                                            }
                                        }
                                );
                            }

                            @Override
                            public void onFail() {
                                // 修改为离线风险点模式
                                for (LocalImage item : images) {
                                    if ("5".equals(item.getAttachMode()))
                                        item.setAttachMode("3");
                                }
                                // 保存已上传图片信息
                                mLocalImageDao.insertList(images);
                                // 保存待上传数据
                                mRiskHttp.insertData(
                                        param.getAppNo(),
                                        param.getPlanNo(),
                                        param.getWtNo()
                                );

                                handleRiskResult(param, listener);
                            }
                        }
                );
            } else {
                // 修改为离线风险点模式
                for (LocalImage item : images) {
                    if ("5".equals(item.getAttachMode()))
                        item.setAttachMode("3");
                }
                // 更新待上传图片信息
                mLocalImageDao.insertList(images);

                // 保存待上传数据
                mRiskHttp.insertData(
                        param.getAppNo(),
                        param.getPlanNo(),
                        param.getWtNo()
                );

                handleRiskResult(param, listener);
            }
        } else {
            // 回调结果给微应用
            listener.complete(
                    1,
                    ToolGson2.getJsonStr(
                            new BaseEntity(
                                    "0",
                                    "数据参数提交错误！"
                            )
                    )
            );
        }
    }

    /**
     * 无网络或成功时风险点的处理
     *
     * @param param    提交参数
     * @param listener 回调
     */
    private void handleRiskResult(
            TicketSaveInfo param,
            BaseOperateRouter.CompleteListener listener
    ) {
        // 更新本地工作票信息
        TicketDetail data = new TicketLocalUtil().getTicketDetailByNo(param.getWtNo());

        if (data != null
                && "1".equals(param.getIsChk())) {
            // 更新本地风险点状态
            data.setEND_MSG("");
            // 更新工作票详情
            mTicketDetail.update(data);
        }

        // 回调结果给微应用
        listener.complete(
                1,
                ToolGson2.getJsonStr(
                        new BaseEntity(
                                "1",
                                "保存成功！"
                        )
                )
        );
    }

    /**
     * 上传本地图片
     *
     * @param imgs     图片列表
     * @param callback 完成回调
     */
    private void uploadPicture(
            final List<LocalImage> imgs,
            final IUploadCallback callback
    ) {
        // 风险点不传图片保存时直接成功
        if (imgs.isEmpty()) {
            callback.onDone();
            return;
        }

        // 图片上传方式
        String model = SPUtils.get("upload-mode", "");

        if ("02".equals(model)) { //图片上传至阿里云
            final ArrayList<String> images = new ArrayList<>();
            for (LocalImage item : imgs)
                images.add(item.getAttachSrc());

            OSSHelper.getInstance()
                    .uploadImages(
                            images,
                            new OnOSSStatusListener() {
                                @Override
                                public void onSuccess(PutObjectResult result, int index) {
                                    if (result != null) {
                                        LocalImage inner = imgs.get(index);
                                        if ("5".equals(inner.getAttachMode()))
                                            inner.setAttachMode("3");
                                        inner.setAttachStatus("02"); //已上传
                                        inner.setAttachLocal(images.get(index));
                                        inner.setAttachSrc(result.getResponseHeader().get("url"));
                                    } else {
                                        if (index == imgs.size()) callback.onDone();
                                        else callback.onFail();
                                    }
                                }
                            }
                    );
        } else { //图片上传至服务器
            final int totalSize = imgs.size(); //文件总数
            final int[] currentSize = {0, 0}; //上传成功失败次数记录

            for (LocalImage item : imgs) {
                try {
                    SingleThreadUtil.executeThread(
                            ZoomWebControler.getInstance()
                                    .getBlockUploadFile(
                                            item.getAttachSrc(),
                                            "/weblogic/app/yxgkzy/image/",
                                            false,
                                            item,
                                            new ZoomWebControler.StatusListener() {
                                                @Override
                                                public void complete(int retCode, Object extra, String result) {
                                                    switch (retCode) {
                                                        case 0:
                                                            currentSize[0]++;
                                                            break;
                                                        case 1:
                                                            currentSize[0]++;
                                                            currentSize[1]++;

                                                            try {
                                                                JSONObject obj = new JSONObject(result);
                                                                LocalImage inner = (LocalImage) extra;
                                                                if ("5".equals(inner.getAttachMode()))
                                                                    inner.setAttachMode("3");
                                                                inner.setAttachStatus("02"); //已上传
                                                                inner.setAttachLocal(inner.getAttachSrc());
                                                                inner.setAttachSrc(obj.optString("filePath"));
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                            break;
                                                    }

                                                    if (currentSize[0] == totalSize) {
                                                        if (currentSize[0] == currentSize[1])
                                                            callback.onDone();
                                                        else callback.onFail();
                                                    }
                                                }
                                            }
                                    )
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 手动触发获取待许可、待终结工作票信息
     *
     * @param context 上下文
     */
    private void getTicketByHand(final Context context) {
        HttpUtil.getLocalTicketDetail(
                context,
                new HttpCallbackInterface() {
                    @Override
                    public void httpSuccess(String result) {
                        try {
                            // 解析数据
                            TicketDetailResult data =
                                    JsonUtils.toBean(result, TicketDetailResult.class);

                            if (data != null
                                    && "1".equals(data.getRT_F())
                                    && data.getDTS() != null
                                    && !data.getDTS().isEmpty()) {
                                Log.i("tiketDetail", data.getDTS().size() + "");

                                // 当前用户ID
                                String userId = SharepreferenceUtil.getUid(context);
                                // 保存本地数据库
                                mTicketDetail.insertList(data.getDTS(), userId);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void httpFailed(int errorCode, String errorMsg) {
                        Log.e("onFail-ticket-by-hand:", errorCode + "：" + errorMsg);
                    }
                }
        );
    }

    /**
     * 手动触发获取一条待许可、待终结工作票信息
     *
     * @param context  上下文
     * @param recordId 工作票ID
     * @param callback 回调
     */
    private void getSingleTicket(
            final Context context,
            String recordId,
            final IUploadCallback callback
    ) {
        // 本地未查询到数据时重新请求接口
        HttpUtil.getSingleTicketDetail(
                context,
                recordId,
                new HttpCallbackInterface() {
                    @Override
                    public void httpSuccess(String result) {
                        try {
                            // 解析数据
                            TicketDetailResult data =
                                    JsonUtils.toBean(result, TicketDetailResult.class);

                            // 数据获取成功且有值
                            if (data != null
                                    && "1".equals(data.getRT_F())
                                    && data.getDTS() != null
                                    && !data.getDTS().isEmpty()) {
                                // 当前用户ID
                                String userId = SharepreferenceUtil.getUid(context);
                                // 插入本地数据库
                                mTicketDetail.insert(data.getDTS().get(0), userId);

                                // 回调成功结果
                                if (callback != null) callback.onDone();
                            } else {
                                // 回调失败结果
                                if (callback != null) callback.onFail();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                            // 回调失败结果
                            if (callback != null) callback.onFail();
                        }
                    }

                    @Override
                    public void httpFailed(int errorCode, String errorMsg) {
                        Log.e(
                                "onFail-singleTicket:",
                                errorCode + "：" + errorMsg
                        );

                        // 回调失败结果
                        if (callback != null) callback.onFail();
                    }
                }
        );
    }

    /**
     * 查询工作票关联防范措施
     *
     * @param context 上下文
     * @param wtNo    工作票编号
     */
    private void getMeasuresByTicket(Context context, String wtNo) {
        HttpUtil.getMeasuresByTicket(
                context,
                wtNo,
                new HttpCallbackInterface() {
                    @Override
                    public void httpSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            JSONArray array = obj.optJSONArray("DTS");
                            if (array != null) {
                                // 解析防范措施
                                ArrayList<TicketMeasure> items =
                                        ToolGson2.jsonToArrayList(
                                                array.toString(),
                                                TicketMeasure.class
                                        );

                                // 保存到本地数据库
                                mTicketMeasure.insertList(items);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void httpFailed(int errorCode, String errorMsg) {
                        Log.e("onFail-measure-by-hand:", errorCode + "：" + errorMsg);
                    }
                });
    }

    /**
     * 上传图片状态接口
     */
    interface IUploadCallback {
        void onDone(); //全部提交成功

        void onFail(); //提交有失败
    }

}
